import React, { Component } from 'react';

import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    Linking,
    Alert, DeviceEventEmitter, FlatList, ActivityIndicator, Platform, Dimensions,
} from 'react-native';
import Header from '../../components/header';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import { getImgUrl } from '../../utils/ComFunction';
import Loading from "../../utils/Loading";
import Constant from '../../utils/Constant';
import NoData from "../../utils/NoData";
import AlertCommonView from "../../components/Tool/AlertCommonView";
import {ToastToUser} from "../../utils/CustomToast";
import SeekItemView from "./seekComponents/SeekItemView"; //全局变量
let navigation;

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

export default class BuyerDetailPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buyerDetail: {},
            tagList: [],
            limitTagList: [],
            allTagList: [],
            // 是否关注
            isFollow: false,
            showTagMore: false,

            isRefresh: false,
            showFoot: false, // true：已加载完成,没有更多数据
            pageNo: 1,
            pageSize: 20,

            // 我发布的求购信息
            seekingList: [],

            // 弹窗
            showAlertCommonView: false,
            showAlertData: {},
            deleteId: null,
            upCarPurchaseId: null, // 当前上下架id

        };
    }
    componentDidMount() {
        this.setLable = DeviceEventEmitter.addListener('BuyerSetLabelPage', (data) => {
            this.loadData();
            this.setState({
                showTagMore: false,
                tagList: this.state.limitTagList,
            })
        })
        this.ApplyCarFormPage = DeviceEventEmitter.addListener('ApplyCarFormPageSave', (data) => {
            if(data.fromPage === 'BuyerDetailPage'){
                this.refreshData()
            }
        })
        this.loadData()
        this.mySeekList()
    }
    componentWillUnmount() {
        if (this.setLable) {
            this.setLable.remove();
        }
        if (this.ApplyCarFormPage) {
            this.ApplyCarFormPage.remove();
        }
    }
    //加载数据
    loadData() {
        //读取页面传入参数
        let params = this.props.route.params;
        let buyerId = params.buyerId
        this.Loading.show();
        HttpUtils.getRequest(HttpUrls.queryBuyerDetail, { buyerId: buyerId })
            .then(result => {
                if (result.code === 0) {
                    let tempTagList = [];
                    let limitTempTagList = [];
                    //判断如果存在标签列表
                    if (result.data?.buyerTags?.length > 0) {
                        //循环标签列表
                        result.data.buyerTags.forEach(tagItem => {
                            if(tagItem.tagValueText !== '不限'){
                                tempTagList.push(tagItem);
                            }
                        })
                    }
                    if (result.data?.limitShowBuyerTags?.length > 0) {
                        //循环标签列表
                        result.data.limitShowBuyerTags.forEach(tagItem => {
                            if(tagItem.tagValueText !== '不限'){
                                limitTempTagList.push(tagItem);
                            }
                        })
                    }

                    this.setState({
                        buyerDetail: result.data,
                        tagList: limitTempTagList,
                        limitTagList: limitTempTagList,
                        allTagList: tempTagList
                    })
                }
            }).finally(e => {this.Loading.hide();})
    }

    // 设置买手标签
    renderRightButton() {
        return (
            <TouchableOpacity
                style={styles.moreContainer}
                activeOpacity={0.8}
                onPress={() => {
                    navigation.navigate('BuyerSetLabelPage');
                }}>
                <Image style={styles.moreIcon} source={require('source/image/edit_car_icon.png')} />
            </TouchableOpacity>
        )
    }

    // 我发布的求购信息
    mySeekList(){
        HttpUtils.postRequest(HttpUrls.getMyPublishPage, { pageNo: this.state.pageNo, pageSize: this.state.pageSize, optionShowCarNum: 1 })
            .then(result => {
                let data = result.data;
                if (data) {
                    let resultList = data.resultList;
                    if (resultList && resultList.length > 0) {
                        this.setState({
                            seekingList: this.state.seekingList.concat(resultList),
                            isRefresh: false,
                        });
                    } else {
                        this.setState({
                            isRefresh: false
                        });
                        if(this.state.seekingList.length > 0){
                            this.setState({
                                showFoot: true,
                            });
                        }
                    }
                } else {
                    this.setState({
                        isRefresh: false,
                    });
                }
            }).finally(e => {
        })
    }


    // 替换城市后缀
    replaceCitySuffix(cityName) {
        if (!cityName) return '';
        return cityName.replace(/(省|市|区|自治区|自治州|特别行政区)$/g, '');
    }
    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'买手主页'} RightButton={() => this.renderRightButton()} />
                <View style={styles.infoContainer}>
                    <View style={{width: '20%'}}>
                        {this.state.buyerDetail?.avatar ? (
                            <Image
                                style={styles.avatarStyle}
                                source={{
                                    uri: getImgUrl(this.state.buyerDetail?.avatar),
                                }}
                            />
                        ) : (
                            <Image
                                source={require('source/image/seekCenter/default_avatar.png')}
                                style={styles.avatarStyle}
                            />
                        )}
                        <Text style={styles.regionTag}>
                            {this.replaceCitySuffix(this.state.buyerDetail?.provinceName) ?? ''} {this.replaceCitySuffix(this.state.buyerDetail?.cityName) ?? '未设置'}
                        </Text>
                    </View>
                    <View style={{width: '80%', marginLeft: 5}}>
                        <Text numberOfLines={1} style={{flexDirection: 'row', width: '100%'}}>
                            <Text style={styles.nameText}>
                                {this.state.buyerDetail?.fullname}
                            </Text>
                            <Text> </Text>
                            <Text style={{fontSize:13, color:'#FFA500', marginLeft: 6}}>
                                @{this.state.buyerDetail?.merchantAbbreviation ?? '暂无'}
                            </Text>
                        </Text>

                        <Text numberOfLines={3} style={styles.introText}>
                            简介: {this.state.buyerDetail?.preferences ?? '暂无'}
                        </Text>
                    </View>
                </View>
                <View style={styles.preferenceContainer}>
                    <Text style={styles.sectionTitle}>偏好标签</Text>
                    <View style={styles.tagsContainer}>
                        {this.state.tagList.map((item, index) => (
                            <View style={styles.tagItem}>
                                <Text key={index} style={styles.tagItemText}>
                                    {item?.tagValueText}
                                </Text>
                            </View>
                        ))}
                        <TouchableOpacity activeOpacity={0.7} style={styles.tagItemMore} onPress={() => {
                            if (!this.state.showTagMore) {
                                this.setState({
                                    tagList: this.state.allTagList
                                })
                            } else {
                                this.setState({
                                    tagList: this.state.limitTagList
                                })
                            }
                            this.setState({
                                showTagMore: !this.state.showTagMore
                            })
                        }}>
                            <Text style={styles.tagItemMoreText}>{this.state.showTagMore ? '收起' : '查看全部'}</Text>
                        </TouchableOpacity>

                        {/*<Text style={styles.flexGrow} />*/}
                    </View>
                </View>

                {this.renderList()}

                <TouchableOpacity onPress={() => {
                    navigation.navigate('ApplyCarFormPage', {
                        fromPage: 'BuyerDetailPage',
                    });
                }} style={styles.saveButton}>
                    <Text style={styles.saveButtonText}>发布求购</Text>
                </TouchableOpacity>

                {/* 弹窗提示 */}
                {
                    this.state.showAlertCommonView ?
                        <AlertCommonView
                            title={this.state.showAlertData.title}
                            content={this.state.showAlertData.content}
                            cancelBtnText={this.state.showAlertData.cancelBtnText}
                            sureBtnText={this.state.showAlertData.sureBtnText}
                            cancelHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                            }}
                            sureHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                                if (this.state.showAlertData.type === 'delete') {
                                    this.deleteCarPurchase()
                                }else if (this.state.showAlertData.type === 'up') { // 上架求购信息
                                    this.upCarPurchase()
                                }else if (this.state.showAlertData.type === 'down') { // 下架求购信息
                                    this.downCarPurchase()
                                }
                            }}
                        />
                        :
                        null
                }

                <Loading onRef={ref => (this.Loading = ref)} />

            </View>
        );
    }

    renderList() {
        return (
            <View
                style={{
                    flex: 1,
                    marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 0 : 0,
                }}>
                <FlatList
                    data={this.state.seekingList}
                    renderItem={this.renderItemView.bind(this)}
                    keyExtractor={(item) => item.id.toString()}
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.3}
                />
                <View style={{height: 90, backgroundColor: '#FFFFFF'}}></View>
            </View>
        );
    }

    // 删除求购
    deleteCarPurchase(){
        HttpUtils.postRequest(HttpUrls.deleteCarPurchase, {
            id: this.state.deleteId
        }).then(result => {
            console.log(result)
            if(result.code === 0){
                ToastToUser("删除成功")
                this.refreshData()
            }else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
    }

    upCarPurchase(){
        console.log('upCarPurchase', '上架')
        HttpUtils.postRequest(HttpUrls.upCarPurchase, {
            id: this.state.upCarPurchaseId
        }).then(result => {
            console.log(result)
            if(result.code === 0){
                ToastToUser("上架成功")
                this.refreshData()
            }else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
    }

    downCarPurchase(){
        console.log('upCarPurchase', '下架')
        HttpUtils.postRequest(HttpUrls.downCarPurchase, {
            id: this.state.upCarPurchaseId
        }).then(result => {
            console.log(result)
            if(result.code === 0){
                ToastToUser("下架成功")
                this.refreshData()
            }else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
    }

    renderItemView({item, index}) {
        return (

            <View style={{  marginHorizontal: 8, borderRadius: 5, marginTop: 10,}} key={item.id}>
                <SeekItemView
                    item={item}
                    buyerId={Constant.userInfo.buyerId}
                    onPress={()=>{
                        navigation.navigate('SeekingDetailPage', {
                            id: item.id,
                        });
                    }}
                    navigation={navigation}
                    onPressDel={()=>{
                        this.setState({
                            deleteId: item.id,
                            showAlertData: {
                                title: '确定删除求购信息?',
                                cancelBtnText: '取消',
                                sureBtnText: '确定',
                                type: 'delete'
                            },
                            showAlertCommonView: true,
                        })
                    }}
                    onPressUpDown={()=>{
                        if(item.status === 1){ // 进行下架操作
                            this.setState({
                                upCarPurchaseId: item.id,
                                showAlertData: {
                                    title: '确定下架求购信息?',
                                    cancelBtnText: '取消',
                                    sureBtnText: '确定',
                                    type: 'down'
                                },
                                showAlertCommonView: true,
                            })
                        }else if (item.status === 2 || item.status === 3) { // 上架操作
                            this.setState({
                                upCarPurchaseId: item.id,
                                showAlertData: {
                                    title: '确定上架求购信息?',
                                    cancelBtnText: '取消',
                                    sureBtnText: '确定',
                                    type: 'up'
                                },
                                showAlertCommonView: true,
                            })
                        }
                    }}
                    onPressEdit={() => {
                        navigation.navigate('ApplyCarFormPage', {
                            id: item.id,
                            fromPage: 'BuyerDetailPage',
                        });
                    }}
                ></SeekItemView>

            </View>
        );
    }

    renderFooter() {
        if (this.state.showFoot) {
            return (
                <View style={styles.footer}>
                    {/*<ActivityIndicator size="small" color="#999999" />*/}
                    <Text style={styles.loadMoreTextStyle}>没有更多数据了</Text>
                </View>
            );
        }else {
            return null;
        }
    }

    //刷新数据
    refreshData = () => {
        this.setState(
            {
                isRefresh: true,
                pageNo: 1,
                seekingList: [],
                showFoot: false,
            },
            function () {
                this.mySeekList();
            },
        );
    };

    _onEndReached() {
        if (this.state.seekingList.length == 0) {
            return;
        }
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot) {
            return null;
        }
        //底部显示正在加载更多数据
        this.setState(
            {
                pageNo: this.state.pageNo + 1,
            },
            function () {
                this.mySeekList();
            },
        );
    }

    renderEmpty() {
        return <NoData Desc="暂未发布求购信息" style={{marginTop: gREM(50)}} />;
    }

}
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F9F9F9',
        flex: 1,
        position: 'relative',
    },
    infoContainer: {
        marginTop: 2,
        backgroundColor: '#fff',
        flexDirection: 'row',
        borderBlockColor: '#E5E5E5',
        padding: 10,
        paddingHorizontal: 15,
    },
    avatarStyle: {
        width: 60,
        height: 60,
        borderRadius: 50,
    },
    moreContainer: {
        position: 'absolute',
        right: 0,
        width: 60,
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center'
    },
    saveButton: {
        position: 'absolute',
        // height: 50,
        bottom: 20,       // 底部距离
        left: 20,         // 左侧留白
        right: 20,        // 右侧留白
        backgroundColor: '#FFE000',
        borderRadius: 25,
        paddingVertical: 15,
        alignItems: 'center',
        justifyContent: 'center'
    },
    saveButtonText: {
        color: '#333333',
        fontSize: 16,
        fontWeight: 'bold',
    },
    nameText: {
        fontSize: 14,
        color: '#333',
        fontWeight: '500',
    },
    introText: {
        fontSize: 12,
        marginTop: 3,
    },
    regionTag: {
        backgroundColor: '#f7f7f2',
        borderRadius: 4,
        paddingVertical: 2,
        paddingHorizontal: 6,
        marginTop: 5,
        fontSize: 12,
        alignSelf: 'flex-start',
        color: '#333333',
    },
    preferenceContainer: {
        marginTop: 1,
        backgroundColor: '#fff',
        // padding: 10,
        paddingHorizontal: 15,
        paddingVertical:15,
    },
    sectionTitle: {
        fontSize: 15,
        color: '#333',
        fontWeight: '500',
    },
    tagsContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 5,
    },
    tagItem: {
        backgroundColor: '#fff399',
        borderRadius: 4,
        paddingVertical: 2,
        paddingHorizontal: 6,
        marginRight: 8,
        marginTop: 5,
    },
    tagItemText: {
        fontSize: 12,
        color: '#333333',
    },
    tagItemMore: {
        paddingVertical: 2,
        paddingHorizontal: 6,
        marginRight: 8,
        marginTop: 5,
        color: '#333333',
    },
    tagItemMoreText: {
        fontSize: 12
    },
    flexGrow: {
        flexGrow: 1
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F9F9F9',
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },
    sepLine: {
        position: 'absolute',
        bottom: 0,
        left: 15,
        width: screenW - 15,
        height: 0.5,
        backgroundColor: '#e4e4e4',
    },

    // 求购item
    actionsContainer: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        backgroundColor: '#fff',
        paddingBottom: 10
    },
    actionButton: {
        flexDirection: 'row',
        padding: 5,
    },
    actionButtonText: {
        fontWeight: 'bold',
        fontSize: 14,
        color: '#333333',
        marginLeft: 5,
    },
    actionImage: {
        width: 20,
        height: 20,
    },

});
